package com.byzoro.controller;

import com.byzoro.pojo.Users;
import com.byzoro.service.UsersService;
import com.byzoro.utils.JsonResult;
import com.byzoro.utils.Upload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
@Controller
@Slf4j
public class UsersController {
    @Autowired
    UsersService usersService;

    @ResponseBody
    @GetMapping("/api/user/list")
    public JsonResult select (@RequestParam("page") int page, @RequestParam("limit") int limit) {
        return usersService.list(page, limit);
    }

    @ResponseBody
    @PostMapping("/api/user/add")
    public JsonResult create (@RequestBody Users param) {
        return usersService.create(param);
    }

    @GetMapping("/userEdit/{id}")
    public String userEdit(@PathVariable("id") int id, Model model) {
        model.addAttribute("id", id);
        return "userEdit";
    }

    @ResponseBody
    @PutMapping("/api/user/update")
    public JsonResult update(@RequestBody Users param) {
        return usersService.update(param);
    }

    @ResponseBody
    @DeleteMapping("/api/user/delete")
    public JsonResult delete(@RequestBody Map<String, String> map) {
        return usersService.delete(Integer.parseInt(map.get("id")));
    }

    @ResponseBody
    @PostMapping("/api/user/upload")
    public JsonResult upload(@RequestParam("file") MultipartFile file) {
        return Upload.upload(file, "head_pic");
    }


    @ResponseBody
    @GetMapping("/api/user/detail")
    public JsonResult detail(@RequestParam("id") int id) {
        return usersService.getUserById(id);
    }
}
